/*
 * j4Win
 *  http://code.google.com/p/j4win/
 *
 * Copyright (C) 2006-2007 Felix Geyer, Moritz Laschinger
 *
 * This file is part of j4Win.
 *
 * j4Win is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * j4Win is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package j4win;

import java.util.Random;

public class KISimple extends KI {
	private Random ran = new Random();
	
	@Override
	protected void requestMove() {
		if (lastCol == -1) {
			move(3);
			return;
		}
		
		int[] me = willPlayerWin(1);
		if (me.length>0) {
			int col;
			if (me.length>1) {
				col = ran.nextInt(me.length);
			}
			else {
				col = 0;
			}
			move(me[col]);
			return;
		}
		
		int[] enemy = willPlayerWin(2);
		if (enemy.length>0) {
			int col;
			if (enemy.length>1) {
				col = ran.nextInt(enemy.length);
			}
			else {
				col = 0;
			}
			move(enemy[col]);
			return;
		}
		
		int[] cols = new int[Field.WIDTH];
		for (int i=0; i<cols.length; ++i)
			cols[i] = 1;
		
		for (int x=0; x<Field.WIDTH; ++x) {
			int y = field.lastStone(x);
			
			if (y == (Field.HEIGHT-1)) {
				cols[x] = 0;
				continue;
			}
			
			for (int col=Math.max(x-1, 0); col<Math.min(x+1, Field.WIDTH-1); ++col) {
				for (int row=Math.max(y-1, 0); row<Math.min(y+1, Field.HEIGHT-1); ++row) {
					if (field.get(x, y)==1) ++cols[x];
				}
			}
		}
		
		int count = 0;
		for (int i=0; i<cols.length; ++i) {
			cols[i] *= cols[i];
			count += cols[i];
		}
		
		int ranNum = ran.nextInt(count)+1;
		
		for (int i=0; i<cols.length; ++i) {
			ranNum -= cols[i];
			if (ranNum <= 0) {
				move(i);
				return;
			}
		}
	}
	
	private int[] willPlayerWin(int player) {
		int[] result = new int[Field.WIDTH];
		int count = 0;
		for (int x=0; x<Field.WIDTH; ++x) {
			if (field.isColFull(x)) continue;
			Field f = field.clone();
			int y = f.add(x, player);
			if ( f.hasPlayerWon(player, x, y) )
				result[count++] = x;
		}

		int[] newResult = new int[count];
		System.arraycopy(result, 0, newResult, 0, newResult.length);
		return newResult;
	}
}
